package com.itita.ww2.web.core;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.smartfoxserver.v2.SmartFoxServer;
import com.smartfoxserver.v2.entities.Zone;
import com.itita.ww2.common.WebProxy;

@SuppressWarnings("serial")
public abstract class AbstractHttpServlet extends HttpServlet {
	private static final Logger logger = LoggerFactory.getLogger(AbstractHttpServlet.class);
	// zoneId
	public static final String ZoneName = "WW2Server";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.getRequestDispatcher("/404.html").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Zone zone = SmartFoxServer.getInstance().getZoneManager().getZoneByName(ZoneName);
		String ret = null;
		if (zone != null) {
			WebProxy proxy = (WebProxy) zone.getProperty("webProxy");
			ret = handleRequest(proxy, req, resp);
		}
		if (ret != null) {
			resp.setCharacterEncoding("utf-8");
			resp.setDateHeader("Expires", -1);
			resp.setHeader("Cache-Control", "no-cache");
			resp.setHeader("Pragma", "no-cache");
			resp.setContentType("text/html; charset=utf-8");
			resp.getWriter().write(ret);
			resp.getWriter().close();
		}
		logger.info("web request: servlet path: {}, path info: {},zone: {}", req.getServletPath(), req.getPathInfo(),
				zone != null ? zone.getName() : "null");
	}

	protected abstract String handleRequest(WebProxy webProxy, HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException;
}
